import struct
import smbus
import time

class Battery:
    def __init__(self, address = 0x36): #初始化I2CBus
        '初始化一个电池实例\n参数：I2C地址'
        self.bus = smbus.SMBus(1)
        self.address = address#0x36

        self.QuickStart()
        self.PowerOnReset()

    def QuickStart(self):
        self.bus.write_word_data(self.address, 0x06,0x4000)

    def PowerOnReset(self):
        self.bus.write_word_data(self.address, 0xfe,0x0054)

    def readVoltage(self):
        read = self.bus.read_word_data(self.address, 2)
        swapped = struct.unpack("<H", struct.pack(">H", read))[0]
        voltage = swapped * 1.25 /1000/16
        return voltage

    def readCapacity(self):
        read = self.bus.read_word_data(self.address, 4)
        swapped = struct.unpack("<H", struct.pack(">H", read))[0]
        capacity = swapped/256
        return capacity
